//
//  SEProfileHeaderView.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/13.
//

import UIKit

enum SEProfileHeaderViewActionType {
    case avator
    case setting
    case name
}

protocol SEProfileHeaderViewDelegate: NSObjectProtocol{
    func profileHeaderViewTapAction(type: SEProfileHeaderViewActionType)
}

class SEProfileHeaderView: UIView {

    weak var delegate: SEProfileHeaderViewDelegate?

    @IBOutlet weak var settingBtn: UIButton!

    @IBOutlet weak var avatorImgView: UIImageView! {
        didSet {
            avatorImgView.layer.cornerRadius = avatorImgView.size.height / 2.0
            avatorImgView.layer.masksToBounds = true
            avatorImgView.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(avatorTapAction))
            avatorImgView.addGestureRecognizer(tap)
        }
    }

    @IBOutlet weak var nameLabel: UILabel! {
        didSet {
            nameLabel.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(nameLabelTapAction))
            nameLabel.addGestureRecognizer(tap)
        }
    }

    @IBAction func settingBtnAction(_ sender: UIButton) {
        delegate?.profileHeaderViewTapAction(type: .setting)
    }

    @objc private func avatorTapAction() {
        delegate?.profileHeaderViewTapAction(type: .avator)
    }

    @objc private func nameLabelTapAction() {
        guard UserDefaults.userNick.isEmpty else { return }
        delegate?.profileHeaderViewTapAction(type: .name)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUI()
    }

    func updateView(viewModel: SEProfileViewModel) {
        nameLabel.text = viewModel.userNick
        avatorImgView.kf.setAvatarImage(urlString:viewModel.avatorImg)
    }

    func setUI() {
        loadNib()
    }

    func loadNib() {
        let view = UINib.init(nibName: String(describing: type(of: self)), bundle: Bundle(for: type(of: self))).instantiate(withOwner: self, options: nil).last as! UIView
        view.frame = bounds
        addSubview(view)
    }

}
